package com.example.navigationdemo.nav.utils;

import android.content.ComponentName;

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.navigation.ActivityNavigator;
import androidx.navigation.NavController;
import androidx.navigation.NavGraph;
import androidx.navigation.NavGraphNavigator;
import androidx.navigation.Navigator;
import androidx.navigation.NavigatorProvider;

import com.example.navigationdemo.nav.model.Destination;
import com.example.navigationdemo.nav.navigator.FixFragmentNavigator;

import java.util.HashMap;
import java.util.Iterator;

/**
 * @author: tuyrt7 on 2020/9/3.
 */
public class NavGraphBuilder {

    public static void build(FragmentActivity context, FragmentManager childFragmentManager, NavController controller,int containerId) {

        NavigatorProvider provider = controller.getNavigatorProvider();
        // NavGraphNavigator 给默认页面提供高航服务
        NavGraph navGraph = new NavGraph(new NavGraphNavigator(provider));
        // FixFragmentNavigator 给fragment导航
        FixFragmentNavigator fragmentNavigator = new FixFragmentNavigator(context, childFragmentManager, containerId);
        provider.addNavigator(fragmentNavigator);
        // ActivityNavigator 给activity导航
        ActivityNavigator activityNavigator = provider.getNavigator(ActivityNavigator.class);

        HashMap<String, Destination> destConfig = AppConfig.getDestConfig();
        Iterator<Destination> iterator = destConfig.values().iterator();
        while (iterator.hasNext()) {
            Destination node = iterator.next();
            if (node.isFragment) {
                FixFragmentNavigator.Destination destination = fragmentNavigator.createDestination();
                destination.setClassName(node.clazzName);
                destination.setId(node.id);
                destination.addDeepLink(node.pathUrl);
                navGraph.addDestination(destination);
            } else {
                ActivityNavigator.Destination destination = activityNavigator.createDestination();
                destination.setComponentName(new ComponentName(AppGlobals.getApplication().getPackageName(),node.clazzName));
                destination.setId(node.id);
                destination.addDeepLink(node.pathUrl);
                navGraph.addDestination(destination);
            }

            if (node.asStarter) {
                navGraph.setStartDestination(node.id);
            }
        }
        controller.setGraph(navGraph);
    }
}
